package com.android.myapplication.view.media;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaFormat;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.myapplication.R;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class AudioRecorderActivity extends Activity {

    private int mAudioSource = MediaRecorder.AudioSource.VOICE_COMMUNICATION;//自动降噪,也尝试过 MIC
    private int mSampleRateInHz = 44100;
    private int mChannelConfig = AudioFormat.CHANNEL_IN_MONO;//单声道
    private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT;//每次采样位数
    private int mMinBufferSize;
    AudioRecord mAudioRecord;

    boolean isRecordering;
    Button btnReorder;

    DataOutputStream outputStream;

    Thread mRecordThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recorder);
        btnReorder =findViewById(R.id.btn_recorder);
        btnReorder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRecordering){
                    stopRecord();
                }else{
                    startRecord();
                }
            }
        });
        findViewById(R.id.btn_play).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mAudioPlay != null) {
                    try {
                        mAudioPlay.playMusic();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }else{
                    // 绑定服务
                    bindService(new Intent(AudioRecorderActivity.this, AudioTrackService.class), connection, BIND_AUTO_CREATE);
                }
            }
        });
        findViewById(R.id.btn_encode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                encode();
            }
        });
    }

    public void onPause(){
        super.onPause();
        stopRecord();
    }

    public void startRecord() {
        if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 100);
            return;
        }
        if (mAudioRecord == null) {
            mMinBufferSize = AudioRecord.getMinBufferSize(mSampleRateInHz,mChannelConfig, mAudioFormat);//计算最小缓冲区

            mAudioRecord = new AudioRecord(mAudioSource, mSampleRateInHz, mChannelConfig, mAudioFormat, mMinBufferSize);
        }
        if (mRecordThread == null) {
            mRecordThread = new Thread(recordRunnable);
            mRecordThread.start();
            btnReorder.setText("结束录制");
        }
    }

    public void stopRecord() {
        isRecordering = false;
    }
    Runnable recordRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                isRecordering = true;

                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
                byte[] list = new byte[mMinBufferSize];
                File file = new File(AudioTrackService.ADUIO_FILE);
                if (!file.exists()){
                    file.createNewFile();
                }
                outputStream = new DataOutputStream(new FileOutputStream(file));
                mAudioRecord.startRecording();
                while (isRecordering) {
                    int len = mAudioRecord.read(list, 0, mMinBufferSize);
//                    for (int i = 0; i < list.length; i++){
//                            list[i] = (byte) (list[i] ^ (i& 0xFF));
//                    }
                    outputStream.write(list, 0, len);
                    AudioView.audioView.setList(list);
                }
                outputStream.close();
                mAudioRecord.stop();
                isRecordering = false;
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AudioRecorderActivity.this, "录制结束", Toast.LENGTH_LONG).show();
                        btnReorder.setText("开始录制");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                isRecordering = false;
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AudioRecorderActivity.this, "录制失败", Toast.LENGTH_LONG).show();
                        btnReorder.setText("开始录制");
                    }
                });

                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                mAudioRecord.stop();
            } finally {
                mRecordThread = null;
            }
        }
    };


    /*******下面是播放代码****/

    @Override
    protected void onStart() {
        super.onStart();

    }

    private IAudioPlay mAudioPlay;

    private ServiceConnection connection = new ServiceConnection() {
        /**
         * 连接到服务
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mAudioPlay = (IAudioPlay) service;
            try {
                mAudioPlay.playMusic();
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }

        /**
         * 断开连接
         * @param name
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解绑服务：注意bindService后 必须要解绑服务，否则会报 连接资源异常
        if (null != connection) {
            unbindService(connection);
        }
    }

    /*******下面是转码代码****/
    public void encode(){
        String src = AudioTrackService.ADUIO_FILE;
        String dst = new File(src).getParent()+"/my_encode.mp3";
        final AudioCodec audioCodec=AudioCodec.newInstance();
        audioCodec.setEncodeType(MediaFormat.MIMETYPE_AUDIO_MPEG);
        audioCodec.setIOPath(src , dst);
        audioCodec.prepare();
        audioCodec.startAsync();
        audioCodec.setOnCompleteListener(new AudioCodec.OnCompleteListener() {
            @Override
            public void completed() {
                audioCodec.release();
            }
        });
    }
}
